Spring Boot(八)之定时任务锁Shedlock

在我们业务开发过程中,经常会有需求做一些定时任务,但是由于定时任务的特殊性,以及一些方法的幂等性要求,在分布式多节点部署的情况下,某个定时任务只需要执行一次。

1. 背景介绍

ShedLock是一个轻量级的分布式定时任务锁组件,使用其可以满足我们上面的技术需求,ShedLock官方简单自我介绍:

ShedLock makes sure that your scheduled tasks are executed at most once at the same time. If a task is being executed on one node, it acquires a lock which prevents execution of the same task from another node (or thread). Please note, that if one task is already being executed on one node, execution on other nodes does not wait, it is simply skipped.

Shedlock从严格意义上来说不是一个分布式任务调度框架,而是一个分布式锁。所谓的分布式锁,解决的核心问题就是各个节点中无法通信的痛点。各个节点并不知道这个定时任务有没有被其他节点的定时器执行,所以理论上只需要有一个各个节点都能够访问到的资源,用这个资源去标记这个定时任务有没有执行就可以了。

2. Shedlock实现

Shedlock实现分布式锁,可以依赖如下组件:

  • JdbcTemplate
  • Mongo
  • DynamoDB
  • DynamoDB 2
  • ZooKeeper (using Curator)
  • Redis (using Spring
  • RedisConnectionFactory)
  • Redis (using Jedis)
  • Hazelcast
  • Couchbase
  • ElasticSearch
  • CosmosDB
  • Cassandra
  • Multi-tenancy

本文主要以来Redis为公共存储,实现定时任务的分布式锁。首先,我们假设你的Spring Boot项目已经引入了Redis,在项目的pom文件中加入依赖:

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-spring</artifactId>
<version>4.14.0</version>
</dependency>

<dependency>
<groupId>net.javacrumbs.shedlock</groupId>
<artifactId>shedlock-provider-redis-spring</artifactId>
<version>4.14.0</version>
</dependency>

开启定时任务锁:

1
2
3
4
5
6
7
8
9
10
@Configuration
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT30S")
public class ShedlockConfig {

@Bean
public LockProvider lockProvider(RedisTemplate redisTemplate) {
return new RedisLockProvider(redisTemplate.getConnectionFactory());
}
}
  • defaultLockAtMostFor = “PT30S”表示默认锁的最大占用时间是30s;

其次,在定时任务方法上,加上注解@SchedulerLock:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 通过设置lockAtMostFor,我们可以确保即使节点死亡,锁也会被释放;
* 通过设置lockAtLeastFor,我们可以确保它在30s内不会执行超过一次;
*/
@Scheduled(cron = "00 12 15 22 * ?")
@SchedulerLock(name = "testTask-1", lockAtMostFor = "30s", lockAtLeastFor = "10s")
public void testTask1() {
LockAssert.assertLocked();
log.info("exec testTask1......");
}

@Scheduled(fixedRate = 10000L)
@SchedulerLock(name = "testTask-2", lockAtMostFor = "10s", lockAtLeastFor = "2s")
public void testTask2() {
LockAssert.assertLocked();
log.info("exec testTask2......");
}

启动多个节点,会发现,每次定时任务只有一个节点执行,定时任务执行后,在Redis里会看到两个key:job-lock:default:testTask-1和job-lock:default:testTask-2。

3. Shedlock原理分析

Shedlock通过AOP,拿到TaskScheduler的行为做代理,并加入分布式锁实现所需要的功能。

image

上锁入口在RedisLockProvider.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@NonNull
public Optional<SimpleLock> lock(@NonNull LockConfiguration lockConfiguration) {
String key = this.buildKey(lockConfiguration.getName());
Expiration expiration = getExpiration(lockConfiguration.getLockAtMostUntil());
return Boolean.TRUE.equals(tryToSetExpiration(this.redisTemplate, key, expiration, SetOption.SET_IF_ABSENT)) ? Optional.of(new RedisLockProvider.RedisLock(key, this.redisTemplate, lockConfiguration)) : Optional.empty();
}

private static Boolean tryToSetExpiration(StringRedisTemplate template, String key, Expiration expiration, SetOption option) {
return (Boolean)template.execute((connection) -> {
byte[] serializedKey = template.getKeySerializer().serialize(key);
byte[] serializedValue = template.getValueSerializer().serialize(String.format("ADDED:%s@%s", Utils.toIsoString(ClockProvider.now()), Utils.getHostname()));
return connection.set(serializedKey, serializedValue, expiration, option);
}, false);
}

可以看出上锁,其实就是Redis的set操作的过程。

任务执行的入口,可以参考net.javacrumbs.shedlock.core.DefaultLockingTaskExecutor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@Override
@NonNull
public <T> TaskResult<T> executeWithLock(@NonNull TaskWithResult<T> task, @NonNull LockConfiguration lockConfig) throws Throwable {
Optional<SimpleLock> lock = lockProvider.lock(lockConfig);
String lockName = lockConfig.getName();

if (alreadyLockedBy(lockName)) {
logger.debug("Already locked '{}'", lockName);
return TaskResult.result(task.call());
} else if (lock.isPresent()) {
try {
LockAssert.startLock(lockName);
logger.debug("Locked '{}', lock will be held at most until {}", lockName, lockConfig.getLockAtMostUntil());
return TaskResult.result(task.call());
} finally {
LockAssert.endLock();
lock.get().unlock();
if (logger.isDebugEnabled()) {
Instant lockAtLeastUntil = lockConfig.getLockAtLeastUntil();
Instant now = ClockProvider.now();
if (lockAtLeastUntil.isAfter(now)) {
logger.debug("Task finished, lock '{}' will be released at {}", lockName, lockAtLeastUntil);
} else {
logger.debug("Task finished, lock '{}' released", lockName);
}
}
}
} else {
logger.debug("Not executing '{}'. It's locked.", lockName);
return TaskResult.notExecuted();
}
}

首先判断lock是否可用,然后再执行任务task.call()。

以上内容就是关于Spring Boot(八)之定时任务锁Shedlock的全部内容了,谢谢你阅读到了这里!

Author:zhaoyh